package com.jie.other.jetpack.room

import android.content.Context
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.jie.other.jetpack.paging.bean.DataPage
import com.jie.other.jetpack.paging.bean.Repo
import com.jie.other.jetpack.paging.db.DataPageDao
import com.jie.other.jetpack.paging.db.RepoDao

@Database(entities = [UserBean::class, Repo::class, DataPage::class],
    version = 4,
    exportSchema = true,
    autoMigrations = [
        AutoMigration(from = 1, to = 2),
        AutoMigration(from = 2, to = 3, spec = AutoMigration2To3::class),
        AutoMigration(from = 3, to = 4, spec = AutoMigration3To4::class),
    ]
)
abstract class AppDataBase : RoomDatabase() {

    abstract fun getUserDao() : UserDao

    abstract fun getRepoDao() : RepoDao
    abstract fun getDataPageDao() : DataPageDao

    companion object {
        private const val DATA_BASE_NAME = "jieStudy.db"
        private var appDataBase: AppDataBase? = null

        /**
         * 获取单例数据库对象
         */
        fun getDataBase(context : Context) : AppDataBase{
            return appDataBase?.let { it }
                ?: Room.databaseBuilder(context, AppDataBase::class.java, DATA_BASE_NAME)
                    .fallbackToDestructiveMigration() // 支持破坏式升级
                    .build()
                    .apply {
                        appDataBase = this
                    }
        }
    }
}